package wangm.repository;

import wangm.bean.ExaminationPaperHistory;
import wangm.util.DBOperatorComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.sql.SQLException;
import java.util.List;

/**
 * 历史试卷 repository
 *
 * @author zk
 * @date 2018-02-24 18:30
 */
@Repository
public class ExaminationPaperHistoryRepository {
    private static Logger logger = LoggerFactory.getLogger(ExaminationTopicRepository.class);
    /**
     * this table Name(same as PaperRepository)
     */
    public static final String thisTableName = "T_EXAMINATION_FINISH_HISTORY";
    /**
     * db operator
     */
    @Autowired
    private DBOperatorComponent dbOperatorComponent;

    /**
     *  根据id查询当前表
     *
     * @param id id
     * @return examinationBean
     */
    public ExaminationPaperHistory getById(String id){
        try {
            return dbOperatorComponent.getById(id,thisTableName,ExaminationPaperHistory.class);
        } catch (SQLException e) {
            logger.error("query " + thisTableName + "fail",e);
            return null;
        }
    }

    /**
     * 保存历史试卷
     *
     * @param paperHistoryBean paperHistoryBean
     */
    public void savePaperHistory(ExaminationPaperHistory paperHistoryBean){
        String insertSql = "INSERT INTO " + thisTableName +"(id, uid, pid, content) VALUES (?,?,?,?)";
        try {
            dbOperatorComponent.update(insertSql,paperHistoryBean.getId(),paperHistoryBean.getUid(),paperHistoryBean.getPid(),paperHistoryBean.getContent());
        } catch (SQLException e) {
            logger.error("insert into"+ thisTableName + "fail" + e.getMessage(),e);
        }
    }

    /**
     * 根据uid 和pid(试卷id) 获取该试卷
     *
     * @param uid uid
     * @param pid pid
     * @return ExaminationPaperHistory
     */
    public ExaminationPaperHistory getByUidAndPid(String uid, String pid){
        String querySql = "select * from " + thisTableName + " where uid = ? and pid = ?";
        try {
            List<ExaminationPaperHistory> resultList = dbOperatorComponent.getBeanList(ExaminationPaperHistory.class,querySql,uid,pid);
            if(!CollectionUtils.isEmpty(resultList)){
                return resultList.get(0);
            }
            return null;
        } catch (SQLException e) {
            logger.error("query" + thisTableName + "fail:",e);
            return null;
        }
    }
}
